package http

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"log"
	"math"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"runtime"
	"runtime/debug"
	"sort"
	"sync"
	"sync/atomic"
	"time"
)

// 定义颜色常量
const (
	colorReset  = "\033[0m"
	colorRed    = "\033[31m"
	colorGreen  = "\033[32m"
	colorYellow = "\033[33m"
	colorBlue   = "\033[34m"
	colorPurple = "\033[35m"
	colorCyan   = "\033[36m"
	colorWhite  = "\033[37m"
	colorBold   = "\033[1m"
)

// RequestResults 存储请求结果
type RequestResults struct {
	ThreadID    int
	Timestamp   time.Time
	ElapsedTime time.Duration
	Success     bool
	StatusCode  int
	Error       string
}

// TestStage 测试阶段
type TestStage struct {
	Threads  int // 目标线程数
	Duration int // 持续时间(秒)
	RampUp   int // 递增到此线程数所需时间(秒)
	RampDown int // 从此线程数递减所需时间(秒)
}

// TestConfig 存储测试配置
type TestConfig struct {
	URL               string
	Method            string
	Headers           map[string]string
	Data              string
	InitialThreads    int
	OutputFile        string
	RequestTimeout    int
	ThinkTime         int
	FollowRedirects   bool
	DisableKeepAlives bool
	TargetTPS         int         // 目标TPS
	Stages            []TestStage // 测试阶段
	// 新增优化参数
	MaxIdleConns        int  // 最大空闲连接数
	IdleConnTimeout     int  // 空闲连接超时时间(秒)
	DisableCompression  bool // 是否禁用压缩
	MaxConnsPerHost     int  // 每个主机的最大连接数
	ResultBatchSize     int  // 结果批量处理大小
	ResultFlushInterval int  // 结果刷新间隔(秒)
}

// TestStats 存储测试统计信息
type TestStats struct {
	TotalRequests      int64
	SuccessfulRequests int64
	ErrorRequests      int64
	ErrorRate          float64
	Throughput         float64
	CurrentTPS         float64 // 当前TPS
	MaxResponseTime    time.Duration
	MinResponseTime    time.Duration
	AvgResponseTime    time.Duration
	MedianResponseTime time.Duration
	P90ResponseTime    time.Duration
	P95ResponseTime    time.Duration
	P99ResponseTime    time.Duration
	Duration           time.Duration
}

// LoadTester 性能测试主结构
type LoadTester struct {
	Config        TestConfig
	Results       []RequestResults
	StartTime     time.Time
	EndTime       time.Time
	ActiveThreads int32
	StopChan      chan struct{}
	ResultChan    chan RequestResults
	ControlChan   chan string
	Wg            sync.WaitGroup
	Lock          sync.Mutex
	TPSController *TPSController
	HTTPClient    *http.Client
	// 新增对象池
	ResultCollector *ResultCollector
	RequestPool     *RequestPool
	ResponsePool    *ResponsePool
	BufferPool      *sync.Pool
	URL             *url.URL
}

// RequestPool 请求对象池
type RequestPool struct {
	pool sync.Pool
}

// NewRequestPool 创建新的请求对象池
func NewRequestPool() *RequestPool {
	return &RequestPool{
		pool: sync.Pool{
			New: func() interface{} {
				return &http.Request{
					Method: "GET",
					Header: make(http.Header),
				}
			},
		},
	}
}

// Get 从池中获取请求对象
func (p *RequestPool) Get() *http.Request {
	req := p.pool.Get().(*http.Request)
	// 重置请求对象
	req.URL = nil
	req.Body = nil
	req.ContentLength = 0
	req.Header = make(http.Header)
	return req
}

// Put 将请求对象放回池中
func (p *RequestPool) Put(req *http.Request) {
	p.pool.Put(req)
}

// ResponsePool 响应对象池
type ResponsePool struct {
	pool sync.Pool
}

// NewResponsePool 创建新的响应对象池
func NewResponsePool() *ResponsePool {
	return &ResponsePool{
		pool: sync.Pool{
			New: func() interface{} {
				return &http.Response{
					Header: make(http.Header),
				}
			},
		},
	}
}

// Get 从池中获取响应对象
func (p *ResponsePool) Get() *http.Response {
	resp := p.pool.Get().(*http.Response)
	// 重置响应对象
	resp.Status = ""
	resp.StatusCode = 0
	resp.Header = make(http.Header)
	resp.Body = nil
	return resp
}

// Put 将响应对象放回池中
func (p *ResponsePool) Put(resp *http.Response) {
	p.pool.Put(resp)
}

// TPSController TPS控制器
type TPSController struct {
	TargetTPS      int32
	ticker         *time.Ticker
	requestPerTick int32
	requestCount   int32
	tickCount      int32
}

// NewTPSController 创建新的TPS控制器
func NewTPSController(targetTPS int) *TPSController {
	// 计算每秒的请求数
	// 我们使用100ms作为tick间隔，这样控制更精细
	tickInterval := 100 * time.Millisecond
	ticksPerSecond := int(time.Second / tickInterval)
	requestPerTick := int32(math.Ceil(float64(targetTPS) / float64(ticksPerSecond)))

	return &TPSController{
		TargetTPS:      int32(targetTPS),
		ticker:         time.NewTicker(tickInterval),
		requestPerTick: requestPerTick,
		requestCount:   0,
		tickCount:      0,
	}
}

// Wait 等待下一个请求时机
func (c *TPSController) Wait() bool {
	if atomic.LoadInt32(&c.TargetTPS) <= 0 {
		return false
	}

	// 如果当前tick的请求数已经达到限制，等待下一个tick
	if atomic.AddInt32(&c.requestCount, 1) > c.requestPerTick {
		<-c.ticker.C
		atomic.StoreInt32(&c.requestCount, 1)
		atomic.AddInt32(&c.tickCount, 1)
		return true
	}

	return false
}

// Stop 停止TPS控制器
func (c *TPSController) Stop() {
	c.ticker.Stop()
}

// ResultCollector 结果收集器
type ResultCollector struct {
	results   chan RequestResults
	batch     []RequestResults
	mu        sync.Mutex
	flush     chan struct{}
	stats     *TestStats
	statsMu   sync.Mutex
	stopChan  chan struct{}
	statsChan chan TestStats
	startTime time.Time // 记录测试开始时间
}

// NewResultCollector 创建新的结果收集器
func NewResultCollector(batchSize int, flushInterval int) *ResultCollector {
	rc := &ResultCollector{
		results:   make(chan RequestResults, batchSize*2),
		batch:     make([]RequestResults, 0, batchSize),
		flush:     make(chan struct{}, 1),
		stats:     &TestStats{},
		stopChan:  make(chan struct{}),
		statsChan: make(chan TestStats, 1),
		startTime: time.Now(), // 初始化开始时间
	}

	go rc.processBatch(flushInterval)
	return rc
}

// Add 添加结果
func (rc *ResultCollector) Add(result RequestResults) {
	rc.results <- result
}

// Stats 获取统计信息
func (rc *ResultCollector) Stats() TestStats {
	rc.statsMu.Lock()
	defer rc.statsMu.Unlock()
	return *rc.stats
}

// StatsChan 获取统计信息通道
func (rc *ResultCollector) StatsChan() <-chan TestStats {
	return rc.statsChan
}

// Stop 停止结果收集器
func (rc *ResultCollector) Stop() {
	close(rc.stopChan)
}

// processBatch 处理批量结果
func (rc *ResultCollector) processBatch(flushInterval int) {
	ticker := time.NewTicker(time.Duration(flushInterval) * time.Second)
	defer ticker.Stop()

	for {
		select {
		case result := <-rc.results:
			rc.mu.Lock()
			rc.batch = append(rc.batch, result)
			if len(rc.batch) >= cap(rc.batch) {
				rc.flushBatch()
			}
			rc.mu.Unlock()

		case <-ticker.C:
			rc.mu.Lock()
			if len(rc.batch) > 0 {
				rc.flushBatch()
			}
			rc.mu.Unlock()

		case <-rc.flush:
			rc.mu.Lock()
			if len(rc.batch) > 0 {
				rc.flushBatch()
			}
			rc.mu.Unlock()

		case <-rc.stopChan:
			rc.mu.Lock()
			if len(rc.batch) > 0 {
				rc.flushBatch()
			}
			rc.mu.Unlock()
			return
		}
	}
}

// flushBatch 刷新批量结果
func (rc *ResultCollector) flushBatch() {
	// 更新统计信息
	rc.statsMu.Lock()
	defer rc.statsMu.Unlock()

	// 计算基本统计
	totalRequests := int64(len(rc.batch)) + rc.stats.TotalRequests
	successfulRequests := rc.stats.SuccessfulRequests
	errorRequests := rc.stats.ErrorRequests

	responseTimes := make([]time.Duration, 0, len(rc.batch))

	for _, result := range rc.batch {
		if result.Success {
			successfulRequests++
		} else {
			errorRequests++
		}
		responseTimes = append(responseTimes, result.ElapsedTime)
	}

	errorRate := float64(errorRequests) / float64(totalRequests) * 100

	// 计算当前TPS（基于最近10秒的结果）
	cutoffTime := time.Now().Add(-10 * time.Second)
	recentCount := 0
	for _, result := range rc.batch {
		if result.Timestamp.After(cutoffTime) {
			recentCount++
		}
	}
	currentTPS := float64(recentCount) / 10.0

	// 使用记录的开始时间计算持续时间
	duration := time.Since(rc.startTime)
	throughput := float64(totalRequests) / duration.Seconds()

	// 排序响应时间
	sort.Slice(responseTimes, func(i, j int) bool {
		return responseTimes[i] < responseTimes[j]
	})

	// 计算百分位数
	var maxRT, minRT, avgRT, medianRT, p90RT, p95RT, p99RT time.Duration
	if len(responseTimes) > 0 {
		maxRT = responseTimes[len(responseTimes)-1]
		minRT = responseTimes[0]

		// 计算平均响应时间
		var totalResponseTime time.Duration
		for _, rt := range responseTimes {
			totalResponseTime += rt
		}
		avgRT = totalResponseTime / time.Duration(len(responseTimes))

		// 使用更精确的百分位数计算方法
		// 使用线性插值法计算百分位数
		percentile := func(p float64) time.Duration {
			if len(responseTimes) == 0 {
				return 0
			}
			if len(responseTimes) == 1 {
				return responseTimes[0]
			}

			// 计算位置
			pos := p * float64(len(responseTimes)-1) / 100
			idx := int(pos)
			fraction := pos - float64(idx)

			if idx >= len(responseTimes)-1 {
				return responseTimes[len(responseTimes)-1]
			}

			// 线性插值
			lower := responseTimes[idx]
			upper := responseTimes[idx+1]
			return lower + time.Duration(fraction*float64(upper-lower))
		}

		medianRT = percentile(50)
		p90RT = percentile(90)
		p95RT = percentile(95)
		p99RT = percentile(99)
	}

	// 更新统计信息
	rc.stats = &TestStats{
		TotalRequests:      totalRequests,
		SuccessfulRequests: successfulRequests,
		ErrorRequests:      errorRequests,
		ErrorRate:          errorRate,
		Throughput:         throughput,
		CurrentTPS:         currentTPS,
		MaxResponseTime:    maxRT,
		MinResponseTime:    minRT,
		AvgResponseTime:    avgRT,
		MedianResponseTime: medianRT,
		P90ResponseTime:    p90RT,
		P95ResponseTime:    p95RT,
		P99ResponseTime:    p99RT,
		Duration:           duration,
	}

	// 发送统计信息更新
	select {
	case rc.statsChan <- *rc.stats:
	default:
	}

	// 清空批次
	rc.batch = rc.batch[:0]
}

// NewLoadTester 创建新的性能测试实例
func NewLoadTester(config TestConfig) *LoadTester {
	// 解析URL
	parsedURL, err := url.Parse(config.URL)
	if err != nil {
		log.Fatalf("解析URL失败: %v", err)
	}

	// 创建HTTP客户端
	transport := &http.Transport{
		MaxIdleConns:        config.MaxIdleConns,
		IdleConnTimeout:     time.Duration(config.IdleConnTimeout) * time.Second,
		DisableCompression:  config.DisableCompression,
		MaxIdleConnsPerHost: config.MaxConnsPerHost,
		MaxConnsPerHost:     config.MaxConnsPerHost,
		DisableKeepAlives:   config.DisableKeepAlives,
		// 优化缓冲区大小
		WriteBufferSize: 16 << 10, // 16KB
		ReadBufferSize:  16 << 10, // 16KB
	}

	client := &http.Client{
		Transport: transport,
		Timeout:   time.Duration(config.RequestTimeout) * time.Second,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			if !config.FollowRedirects {
				return http.ErrUseLastResponse
			}
			return nil
		},
	}

	// 创建请求池
	// 创建对象池
	requestPool := NewRequestPool()
	responsePool := NewResponsePool()

	bufferPool := &sync.Pool{
		New: func() interface{} {
			return bytes.NewBuffer(make([]byte, 0, 256))
		},
	}

	// 创建结果收集器
	resultCollector := NewResultCollector(config.ResultBatchSize, config.ResultFlushInterval)

	return &LoadTester{
		Config:          config,
		Results:         make([]RequestResults, 0),
		StopChan:        make(chan struct{}),
		ResultChan:      make(chan RequestResults, config.ResultBatchSize*2),
		ControlChan:     make(chan string, 100),
		HTTPClient:      client,
		ResultCollector: resultCollector,
		RequestPool:     requestPool,
		ResponsePool:    responsePool,
		BufferPool:      bufferPool,
		URL:             parsedURL,
	}
}

// MakeRequest 执行HTTP请求
func (lt *LoadTester) MakeRequest(threadID int) {
	// 如果设置了目标TPS，使用TPS控制器
	if lt.TPSController != nil {
		lt.TPSController.Wait()
	}

	startTime := time.Now()

	// 从池中获取请求对象和缓冲区
	req := lt.RequestPool.Get()
	buf := lt.BufferPool.Get().(*bytes.Buffer)
	buf.Reset()

	// 确保将对象放回池中
	defer lt.RequestPool.Put(req)
	defer lt.BufferPool.Put(buf)

	// 创建请求
	var err error

	if lt.Config.Method == "GET" {
		req.Method = "GET"
		req.URL = lt.URL
		req.Body = nil
	} else {
		req.Method = lt.Config.Method
		req.URL = lt.URL
		buf.WriteString(lt.Config.Data)
		req.Body = io.NopCloser(buf)
		req.ContentLength = int64(buf.Len())
	}

	// 设置请求头
	for key, value := range lt.Config.Headers {
		req.Header.Set(key, value)
	}

	// 发送请求
	resp, err := lt.HTTPClient.Do(req)
	elapsedTime := time.Since(startTime)

	// 设置请求头
	for key, value := range lt.Config.Headers {
		req.Header.Set(key, value)
	}

	// 发送请求
	resp, err = lt.HTTPClient.Do(req)
	elapsedTime = time.Since(startTime)

	// 处理响应
	var statusCode int
	var success bool

	if err != nil {
		lt.ResultChan <- RequestResults{
			ThreadID:    threadID,
			Timestamp:   time.Now(),
			ElapsedTime: elapsedTime,
			Success:     false,
			Error:       fmt.Sprintf("请求失败: %v", err),
		}
		return
	}

	// 从响应中获取信息
	statusCode = resp.StatusCode
	success = resp.StatusCode < 400

	// 关闭响应体
	func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			fmt.Println("Error closing body")
		}
	}(resp.Body)

	// 发送结果
	lt.ResultChan <- RequestResults{
		ThreadID:    threadID,
		Timestamp:   time.Now(),
		ElapsedTime: elapsedTime,
		Success:     success,
		StatusCode:  statusCode,
		Error:       "",
	}

	// 思考时间
	if lt.Config.ThinkTime > 0 {
		time.Sleep(time.Duration(lt.Config.ThinkTime) * time.Millisecond)
	}
}

// Worker 工作线程函数
func (lt *LoadTester) Worker(threadID int) {
	defer lt.Wg.Done()

	atomic.AddInt32(&lt.ActiveThreads, 1)
	defer atomic.AddInt32(&lt.ActiveThreads, -1)

	for {
		select {
		case <-lt.StopChan:
			return
		case instruction := <-lt.ControlChan:
			if instruction == "STOP" {
				return
			}
		default:
			lt.MakeRequest(threadID)
		}
	}
}

// AdjustThreads 调整线程数
func (lt *LoadTester) AdjustThreads(targetThreads, stepThreads, stepTime int, operation string) {
	currentThreads := int(atomic.LoadInt32(&lt.ActiveThreads))

	if operation == "increase" {
		for currentThreads < targetThreads {
			// 计算本次要增加的线程数
			threadsToAdd := stepThreads
			if currentThreads+threadsToAdd > targetThreads {
				threadsToAdd = targetThreads - currentThreads
			}

			// 创建新线程
			for i := 0; i < threadsToAdd; i++ {
				lt.Wg.Add(1)
				go lt.Worker(len(lt.Results) + i)
			}

			currentThreads = int(atomic.LoadInt32(&lt.ActiveThreads))
			fmt.Printf("当前线程数: %d\n", currentThreads)

			// 等待下一次调整
			time.Sleep(time.Duration(stepTime) * time.Second)
		}
	} else { // decrease
		for currentThreads > targetThreads {
			// 计算本次要减少的线程数
			threadsToRemove := stepThreads
			if currentThreads-threadsToRemove < targetThreads {
				threadsToRemove = currentThreads - targetThreads
			}

			// 发送停止指令给部分线程
			for i := 0; i < threadsToRemove; i++ {
				lt.ControlChan <- "STOP"
			}

			// 等待线程结束
			time.Sleep(time.Duration(stepTime) * time.Second)

			currentThreads = int(atomic.LoadInt32(&lt.ActiveThreads))
			fmt.Printf("当前线程数: %d\n", currentThreads)
		}
	}
}

// CollectResults 收集结果
func (lt *LoadTester) CollectResults() {
	for result := range lt.ResultChan {
		lt.ResultCollector.Add(result)

		lt.Lock.Lock()
		lt.Results = append(lt.Results, result)
		lt.Lock.Unlock()
	}
}

// CalculateStats 计算统计数据
func (lt *LoadTester) CalculateStats() TestStats {
	if len(lt.Results) == 0 {
		return TestStats{}
	}

	// 计算基本统计
	totalRequests := int64(len(lt.Results))
	successfulRequests := int64(0)
	errorRequests := int64(0)

	responseTimes := make([]time.Duration, 0, len(lt.Results))

	for _, result := range lt.Results {
		if result.Success {
			successfulRequests++
		} else {
			errorRequests++
		}
		responseTimes = append(responseTimes, result.ElapsedTime)
	}

	errorRate := float64(errorRequests) / float64(totalRequests) * 100

	// 计算测试持续时间
	duration := lt.EndTime.Sub(lt.StartTime)

	// 计算TPS和吞吐量
	tps := float64(successfulRequests) / duration.Seconds()
	throughput := float64(totalRequests) / duration.Seconds()

	// 排序响应时间
	sort.Slice(responseTimes, func(i, j int) bool {
		return responseTimes[i] < responseTimes[j]
	})

	// 计算百分位数
	var maxRT, minRT, avgRT, medianRT, p90RT, p95RT, p99RT time.Duration
	if len(responseTimes) > 0 {
		maxRT = responseTimes[len(responseTimes)-1]
		minRT = responseTimes[0]

		// 计算平均响应时间
		var totalResponseTime time.Duration
		for _, rt := range responseTimes {
			totalResponseTime += rt
		}
		avgRT = totalResponseTime / time.Duration(len(responseTimes))

		// 使用更精确的百分位数计算方法
		// 使用线性插值法计算百分位数
		percentile := func(p float64) time.Duration {
			if len(responseTimes) == 0 {
				return 0
			}
			if len(responseTimes) == 1 {
				return responseTimes[0]
			}

			// 计算位置
			pos := p * float64(len(responseTimes)-1) / 100
			idx := int(pos)
			fraction := pos - float64(idx)

			if idx >= len(responseTimes)-1 {
				return responseTimes[len(responseTimes)-1]
			}

			// 线性插值
			lower := responseTimes[idx]
			upper := responseTimes[idx+1]
			return lower + time.Duration(fraction*float64(upper-lower))
		}

		medianRT = percentile(50)
		p90RT = percentile(90)
		p95RT = percentile(95)
		p99RT = percentile(99)
	}

	return TestStats{
		TotalRequests:      totalRequests,
		SuccessfulRequests: successfulRequests,
		ErrorRequests:      errorRequests,
		ErrorRate:          errorRate,
		Throughput:         throughput,
		CurrentTPS:         tps,
		MaxResponseTime:    maxRT,
		MinResponseTime:    minRT,
		AvgResponseTime:    avgRT,
		MedianResponseTime: medianRT,
		P90ResponseTime:    p90RT,
		P95ResponseTime:    p95RT,
		P99ResponseTime:    p99RT,
		Duration:           duration,
	}
}

// DisplayStats 显示统计信息
func (lt *LoadTester) DisplayStats() {
	ticker := time.NewTicker(2 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			stats := lt.ResultCollector.Stats()

			// 清屏
			fmt.Print("\033[H\033[2J")

			// 显示统计信息
			fmt.Println(colorBold + colorCyan + "========== 性能测试实时统计 ==========" + colorReset)
			fmt.Println(colorBold + colorWhite + "测试URL: " + colorReset + colorYellow + lt.Config.URL + colorReset)
			fmt.Println(colorBold + colorWhite + "测试方法: " + colorReset + colorYellow + lt.Config.Method + colorReset)
			fmt.Println(colorBold + colorWhite + "测试持续时间: " + colorReset + colorYellow + fmt.Sprintf("%.2f 秒", stats.Duration.Seconds()) + colorReset)
			fmt.Println(colorBold + colorWhite + "当前线程数: " + colorReset + colorGreen + fmt.Sprintf("%d", atomic.LoadInt32(&lt.ActiveThreads)) + colorReset)

			// 请求统计
			fmt.Println(colorBold + colorPurple + "----- 请求统计 -----" + colorReset)
			fmt.Println(colorWhite + "总请求数: " + colorReset + colorCyan + fmt.Sprintf("%d", stats.TotalRequests) + colorReset)
			fmt.Println(colorWhite + "成功请求数: " + colorReset + colorGreen + fmt.Sprintf("%d", stats.SuccessfulRequests) + colorReset)
			fmt.Println(colorWhite + "错误请求数: " + colorReset + colorRed + fmt.Sprintf("%d", stats.ErrorRequests) + colorReset)

			// 错误率根据值显示不同颜色
			errorRateColor := colorGreen
			if stats.ErrorRate > 5 {
				errorRateColor = colorRed
			} else if stats.ErrorRate > 1 {
				errorRateColor = colorYellow
			}
			fmt.Println(colorWhite + "错误率: " + colorReset + errorRateColor + fmt.Sprintf("%.2f%%", stats.ErrorRate) + colorReset)

			// 性能统计
			fmt.Println(colorBold + colorPurple + "----- 性能统计 -----" + colorReset)
			fmt.Println(colorWhite + "吞吐量: " + colorReset + colorBlue + fmt.Sprintf("%.2f 请求/秒", stats.Throughput) + colorReset)
			fmt.Println(colorWhite + "当前TPS: " + colorReset + colorBlue + fmt.Sprintf("%.2f 事务/秒", stats.CurrentTPS) + colorReset)

			// 响应时间统计
			fmt.Println(colorBold + colorPurple + "----- 响应时间 -----" + colorReset)

			// 最大响应时间根据值显示不同颜色
			maxRTColor := colorGreen
			if float64(stats.MaxResponseTime.Nanoseconds())/1e6 > 1000 {
				maxRTColor = colorRed
			} else if float64(stats.MaxResponseTime.Nanoseconds())/1e6 > 500 {
				maxRTColor = colorYellow
			}
			fmt.Println(colorWhite + "最大响应时间: " + colorReset + maxRTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.MaxResponseTime.Nanoseconds())/1e6) + colorReset)

			// 最小响应时间
			fmt.Println(colorWhite + "最小响应时间: " + colorReset + colorGreen + fmt.Sprintf("%.2f 毫秒", float64(stats.MinResponseTime.Nanoseconds())/1e6) + colorReset)

			// 平均响应时间根据值显示不同颜色
			avgRTColor := colorGreen
			if float64(stats.AvgResponseTime.Nanoseconds())/1e6 > 500 {
				avgRTColor = colorRed
			} else if float64(stats.AvgResponseTime.Nanoseconds())/1e6 > 200 {
				avgRTColor = colorYellow
			}
			fmt.Println(colorWhite + "平均响应时间: " + colorReset + avgRTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.AvgResponseTime.Nanoseconds())/1e6) + colorReset)

			// 中位数响应时间
			fmt.Println(colorWhite + "中位数响应时间: " + colorReset + colorYellow + fmt.Sprintf("%.2f 毫秒", float64(stats.MedianResponseTime.Nanoseconds())/1e6) + colorReset)

			// 90%响应时间根据值显示不同颜色
			p90RTColor := colorGreen
			if float64(stats.P90ResponseTime.Nanoseconds())/1e6 > 800 {
				p90RTColor = colorRed
			} else if float64(stats.P90ResponseTime.Nanoseconds())/1e6 > 400 {
				p90RTColor = colorYellow
			}
			fmt.Println(colorWhite + "90% 响应时间: " + colorReset + p90RTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.P90ResponseTime.Nanoseconds())/1e6) + colorReset)

			// 95%响应时间根据值显示不同颜色
			p95RTColor := colorGreen
			if float64(stats.P95ResponseTime.Nanoseconds())/1e6 > 1000 {
				p95RTColor = colorRed
			} else if float64(stats.P95ResponseTime.Nanoseconds())/1e6 > 500 {
				p95RTColor = colorYellow
			}
			fmt.Println(colorWhite + "95% 响应时间: " + colorReset + p95RTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.P95ResponseTime.Nanoseconds())/1e6) + colorReset)

			// 99%响应时间根据值显示不同颜色
			p99RTColor := colorGreen
			if float64(stats.P99ResponseTime.Nanoseconds())/1e6 > 1500 {
				p99RTColor = colorRed
			} else if float64(stats.P99ResponseTime.Nanoseconds())/1e6 > 800 {
				p99RTColor = colorYellow
			}
			fmt.Println(colorWhite + "99% 响应时间: " + colorReset + p99RTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.P99ResponseTime.Nanoseconds())/1e6) + colorReset)

			fmt.Println(colorBold + colorCyan + "=====================================" + colorReset)

		case <-lt.StopChan:
			return
		}
	}
}

// GenerateReport 生成最终报告
func (lt *LoadTester) GenerateReport() {
	stats := lt.CalculateStats()

	// 打印报告
	fmt.Println("\n" + colorBold + colorCyan + "========== 性能测试最终报告 ==========" + colorReset)
	fmt.Println(colorBold + colorWhite + "测试URL: " + colorReset + colorYellow + lt.Config.URL + colorReset)
	fmt.Println(colorBold + colorWhite + "测试方法: " + colorReset + colorYellow + lt.Config.Method + colorReset)
	fmt.Println(colorBold + colorWhite + "测试持续时间: " + colorReset + colorYellow + fmt.Sprintf("%.2f 秒", stats.Duration.Seconds()) + colorReset)

	// 请求统计
	fmt.Println(colorBold + colorPurple + "----- 请求统计 -----" + colorReset)
	fmt.Println(colorWhite + "总请求数: " + colorReset + colorCyan + fmt.Sprintf("%d", stats.TotalRequests) + colorReset)
	fmt.Println(colorWhite + "成功请求数: " + colorReset + colorGreen + fmt.Sprintf("%d", stats.SuccessfulRequests) + colorReset)
	fmt.Println(colorWhite + "错误请求数: " + colorReset + colorRed + fmt.Sprintf("%d", stats.ErrorRequests) + colorReset)

	// 错误率根据值显示不同颜色
	errorRateColor := colorGreen
	if stats.ErrorRate > 5 {
		errorRateColor = colorRed
	} else if stats.ErrorRate > 1 {
		errorRateColor = colorYellow
	}
	fmt.Println(colorWhite + "错误率: " + colorReset + errorRateColor + fmt.Sprintf("%.2f%%", stats.ErrorRate) + colorReset)

	// 性能统计
	fmt.Println(colorBold + colorPurple + "----- 性能统计 -----" + colorReset)
	fmt.Println(colorWhite + "吞吐量: " + colorReset + colorBlue + fmt.Sprintf("%.2f 请求/秒", stats.Throughput) + colorReset)
	fmt.Println(colorWhite + "平均TPS: " + colorReset + colorBlue + fmt.Sprintf("%.2f 事务/秒", stats.CurrentTPS) + colorReset)

	// 响应时间统计
	fmt.Println(colorBold + colorPurple + "----- 响应时间 -----" + colorReset)

	// 最大响应时间根据值显示不同颜色
	maxRTColor := colorGreen
	if float64(stats.MaxResponseTime.Nanoseconds())/1e6 > 1000 {
		maxRTColor = colorRed
	} else if float64(stats.MaxResponseTime.Nanoseconds())/1e6 > 500 {
		maxRTColor = colorYellow
	}
	fmt.Println(colorWhite + "最大响应时间: " + colorReset + maxRTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.MaxResponseTime.Nanoseconds())/1e6) + colorReset)

	// 最小响应时间
	fmt.Println(colorWhite + "最小响应时间: " + colorReset + colorGreen + fmt.Sprintf("%.2f 毫秒", float64(stats.MinResponseTime.Nanoseconds())/1e6) + colorReset)

	// 平均响应时间根据值显示不同颜色
	avgRTColor := colorGreen
	if float64(stats.AvgResponseTime.Nanoseconds())/1e6 > 500 {
		avgRTColor = colorRed
	} else if float64(stats.AvgResponseTime.Nanoseconds())/1e6 > 200 {
		avgRTColor = colorYellow
	}
	fmt.Println(colorWhite + "平均响应时间: " + colorReset + avgRTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.AvgResponseTime.Nanoseconds())/1e6) + colorReset)

	// 中位数响应时间
	fmt.Println(colorWhite + "中位数响应时间: " + colorReset + colorYellow + fmt.Sprintf("%.2f 毫秒", float64(stats.MedianResponseTime.Nanoseconds())/1e6) + colorReset)

	// 90%响应时间根据值显示不同颜色
	p90RTColor := colorGreen
	if float64(stats.P90ResponseTime.Nanoseconds())/1e6 > 800 {
		p90RTColor = colorRed
	} else if float64(stats.P90ResponseTime.Nanoseconds())/1e6 > 400 {
		p90RTColor = colorYellow
	}
	fmt.Println(colorWhite + "90% 响应时间: " + colorReset + p90RTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.P90ResponseTime.Nanoseconds())/1e6) + colorReset)

	// 95%响应时间根据值显示不同颜色
	p95RTColor := colorGreen
	if float64(stats.P95ResponseTime.Nanoseconds())/1e6 > 1000 {
		p95RTColor = colorRed
	} else if float64(stats.P95ResponseTime.Nanoseconds())/1e6 > 500 {
		p95RTColor = colorYellow
	}
	fmt.Println(colorWhite + "95% 响应时间: " + colorReset + p95RTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.P95ResponseTime.Nanoseconds())/1e6) + colorReset)

	// 99%响应时间根据值显示不同颜色
	p99RTColor := colorGreen
	if float64(stats.P99ResponseTime.Nanoseconds())/1e6 > 1500 {
		p99RTColor = colorRed
	} else if float64(stats.P99ResponseTime.Nanoseconds())/1e6 > 800 {
		p99RTColor = colorYellow
	}
	fmt.Println(colorWhite + "99% 响应时间: " + colorReset + p99RTColor + fmt.Sprintf("%.2f 毫秒", float64(stats.P99ResponseTime.Nanoseconds())/1e6) + colorReset)

	fmt.Println(colorBold + colorCyan + "=====================================" + colorReset)

	// 如果指定了输出文件，则保存结果
	if lt.Config.OutputFile != "" {
		lt.SaveResults()
	}
}

// SaveResults 保存结果到文件
func (lt *LoadTester) SaveResults() {
	file, err := os.Create(lt.Config.OutputFile)
	if err != nil {
		fmt.Printf("创建输出文件失败: %v\n", err)
		return
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {

		}
	}(file)

	writer := bufio.NewWriter(file)
	defer func(writer *bufio.Writer) {
		err := writer.Flush()
		if err != nil {
			fmt.Printf("刷新CSV文件失败: %v\n", err)
		}
	}(writer)

	// 写入表头
	_, err = writer.WriteString("ThreadID,Timestamp,ElapsedTime(ms),Success,StatusCode,Error\n")
	if err != nil {
		fmt.Printf("写入CSV表头失败: %v\n", err)
		return
	}

	// 写入数据
	for _, result := range lt.Results {
		line := fmt.Sprintf("%d,%s,%.2f,%t,%d,%s\n",
			result.ThreadID,
			result.Timestamp.Format(time.RFC3339),
			float64(result.ElapsedTime.Nanoseconds())/1e6,
			result.Success,
			result.StatusCode,
			result.Error,
		)
		_, err = writer.WriteString(line)
		if err != nil {
			fmt.Printf("写入CSV数据失败: %v\n", err)
			return
		}
	}

	fmt.Printf("结果已保存到: %s\n", lt.Config.OutputFile)
}

// RunStages 运行多阶段测试
func (lt *LoadTester) RunStages() {
	fmt.Printf("开始多阶段性能测试: %s\n", lt.Config.URL)

	// 记录开始时间
	lt.StartTime = time.Now()

	// 初始化TPS控制器
	if lt.Config.TargetTPS > 0 {
		lt.TPSController = NewTPSController(lt.Config.TargetTPS)
		defer lt.TPSController.Stop()
		fmt.Printf("目标TPS: %d\n", lt.Config.TargetTPS)
	}

	// 启动结果显示器
	go lt.DisplayStats()

	// 启动结果收集器
	go lt.CollectResults()

	// 创建初始线程
	for i := 0; i < lt.Config.InitialThreads; i++ {
		lt.Wg.Add(1)
		go lt.Worker(i)
	}

	fmt.Printf("初始线程数: %d\n", lt.Config.InitialThreads)

	// 运行各个阶段
	for i, stage := range lt.Config.Stages {
		fmt.Printf("\n=== 阶段 %d ===\n", i+1)
		fmt.Printf("目标线程数: %d\n", stage.Threads)
		fmt.Printf("持续时间: %d 秒\n", stage.Duration)
		fmt.Printf("递增时间: %d 秒\n", stage.RampUp)
		fmt.Printf("递减时间: %d 秒\n", stage.RampDown)

		// 递增到目标线程数
		if stage.RampUp > 0 {
			fmt.Println("开始递增线程...")
			stepTime := 1 // 每秒检查一次
			stepThreads := int(math.Ceil(float64(stage.Threads-int(atomic.LoadInt32(&lt.ActiveThreads))) / float64(stage.RampUp)))
			if stepThreads < 1 {
				stepThreads = 1
			}
			lt.AdjustThreads(
				stage.Threads,
				stepThreads,
				stepTime,
				"increase",
			)
		} else {
			// 直接设置到目标线程数
			threadsToAdd := stage.Threads - int(atomic.LoadInt32(&lt.ActiveThreads))
			for i := 0; i < threadsToAdd; i++ {
				lt.Wg.Add(1)
				go lt.Worker(len(lt.Results) + i)
			}
			fmt.Printf("当前线程数: %d\n", atomic.LoadInt32(&lt.ActiveThreads))
		}

		// 稳定运行
		fmt.Printf("达到目标线程数 %d，稳定运行 %d 秒...\n", stage.Threads, stage.Duration)
		time.Sleep(time.Duration(stage.Duration) * time.Second)

		// 如果是最后一个阶段，不需要递减
		if i == len(lt.Config.Stages)-1 {
			break
		}

		// 递减线程
		if stage.RampDown > 0 {
			fmt.Println("开始递减线程...")
			nextStageThreads := 0
			if i+1 < len(lt.Config.Stages) {
				nextStageThreads = lt.Config.Stages[i+1].Threads
			}

			stepTime := 1 // 每秒检查一次
			stepThreads := int(math.Ceil(float64(int(atomic.LoadInt32(&lt.ActiveThreads))-nextStageThreads) / float64(stage.RampDown)))
			if stepThreads < 1 {
				stepThreads = 1
			}
			lt.AdjustThreads(
				nextStageThreads,
				stepThreads,
				stepTime,
				"decrease",
			)
		} else {
			// 直接递减到下一阶段的线程数或0
			nextStageThreads := 0
			if i+1 < len(lt.Config.Stages) {
				nextStageThreads = lt.Config.Stages[i+1].Threads
			}

			threadsToRemove := int(atomic.LoadInt32(&lt.ActiveThreads)) - nextStageThreads
			for i := 0; i < threadsToRemove; i++ {
				lt.ControlChan <- "STOP"
			}
			time.Sleep(1 * time.Second) // 等待线程结束
			fmt.Printf("当前线程数: %d\n", atomic.LoadInt32(&lt.ActiveThreads))
		}
	}

	// 递减所有线程
	fmt.Println("开始递减所有线程...")
	lt.AdjustThreads(
		0,
		int(atomic.LoadInt32(&lt.ActiveThreads)),
		1,
		"decrease",
	)

	// 等待所有线程结束
	lt.Wg.Wait()

	// 关闭结果通道
	close(lt.ResultChan)

	// 停止结果收集器
	lt.ResultCollector.Stop()

	// 记录结束时间
	lt.EndTime = time.Now()

	// 生成最终报告
	lt.GenerateReport()
}

// SetupSignalHandling 设置信号处理
func (lt *LoadTester) SetupSignalHandling() {
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, os.Interrupt)

	go func() {
		<-sigChan
		fmt.Println("接收到终止信号，正在停止测试...")
		close(lt.StopChan)
	}()
}

// init 初始化函数
func init() {
	// 设置GOMAXPROCS为CPU核心数
	runtime.GOMAXPROCS(runtime.NumCPU())

	// 调整垃圾回收参数
	debug.SetGCPercent(100) // 默认值是100，可以适当增加以减少GC频率

	// 设置内存限制
	debug.SetMemoryLimit(12 * 1024 * 1024 * 1024) // 12GB
}
